package com.lihang0328.groupmessageangel;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ContextActivity extends AppCompatActivity {
    private int comeFrom = 1;
    private String EXCEL_PATH = "";
    public final int EXCEL_SELECT_CODE = 10001;
    public final int TXT_SELECT_CODE = 10002;
    public final int LIST_SELECT_CODE = 10003;
    private ListView mListView;
    private SimpleAdapter mAdapter;
    private int haveChooseNum = 0;
    private Button successChoose;
    private Button chooseMore;
    private ImageView chooseAll;
    private RelativeLayout relativeLayoutChooseAll;
    private Boolean haveChooseAll = false;
    private TextView haveChoose;
    private TextView numOfContext;
    private static List<Map<String, Object>> list_data;
    private static boolean[] listOfChooseNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_context);
        //联系人list
        mListView = (ListView) findViewById(R.id.listview_contextActivity);
        haveChoose = (TextView) findViewById(R.id.tv_numofContextChoose_contextActivity);
        numOfContext = (TextView) findViewById(R.id.tv_numofContext_contextActivity);
        chooseAll = (ImageView) findViewById(R.id.cb_chooseAll_contextActivity);

        relativeLayoutChooseAll = (RelativeLayout) findViewById(R.id.chooseAllRelativeLayout_contextActivity);
        //联系人反选
        relativeLayoutChooseAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (haveChooseAll) unChooseAll();
                else chooseAll();
            }
        });
        chooseMore = (Button) findViewById(R.id.btn_choose_more);
        //手动添加联系人
        chooseMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("PATH", EXCEL_PATH);
                bundle.putString("ORIGIN", String.valueOf(comeFrom));
                Intent intent = new Intent(ContextActivity.this, AddContract.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        successChoose = (Button) findViewById(R.id.btn_successsChoose_context);
        //选择完毕
        successChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getChooseNameList().size() == 0) {
                    Toast.makeText(ContextActivity.this, "你还未选择任何的联系人", Toast.LENGTH_SHORT).show();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("PATH", EXCEL_PATH);
                    bundle.putString("ORIGIN", String.valueOf(comeFrom));
                    Intent intent = new Intent(ContextActivity.this, SendMessageActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                }
            }
        });
        getList();
    }

    /**
     * 加载联系人列表
     */
    protected void getList() {
        haveChooseNum = 0;
        haveChooseAll = false;
        //联系人list
        mListView = (ListView) findViewById(R.id.listview_contextActivity);
        haveChoose = (TextView) findViewById(R.id.tv_numofContextChoose_contextActivity);
        numOfContext = (TextView) findViewById(R.id.tv_numofContext_contextActivity);
        chooseAll = (ImageView) findViewById(R.id.cb_chooseAll_contextActivity);
        if (getIntent() != null) {
            EXCEL_PATH = getIntent().getStringExtra("PATH");
            comeFrom = Integer.parseInt(getIntent().getStringExtra("ORIGIN"));
        }
        if (comeFrom == LIST_SELECT_CODE) list_data = FileUtils.readAddress(this);
        else list_data = FileUtils.readExcel(this, EXCEL_PATH);
        System.out.println("lihang2:" + EXCEL_PATH);
        System.out.println("lihang2:listdata: " + list_data.get(0).get("Name") + " " + list_data.size());
        listOfChooseNum = new boolean[list_data.size()];
        Arrays.fill(listOfChooseNum, false);
        for(int i = 0; i < list_data.size(); ++i) {
            if(listOfChooseNum[i]) System.out.print("lihang2list:" + list_data.get(i).get("Name"));
        }
        mAdapter = new SimpleAdapter(this, list_data, R.layout.list_item_context, new String[]{"Name", "Phone"}, new int[]{R.id.name_list_item_context, R.id.phone_list_item_context});
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("lihang2list: "+id + " " + position);
                System.out.println(view);
                ImageView cb = (ImageView) view.findViewById(R.id.cb_list_item_context);
                if (listOfChooseNum[position]) {
                    cb.setImageResource(R.drawable.checkbox_uncheck);
                    listOfChooseNum[position] = false;
                } else {
                    System.out.println("lihang2:choose" + position);
                    cb.setImageResource(R.drawable.checkbox_check);
                    listOfChooseNum[position] = true;
                }
                haveChooseNum = 0;
                for (int i = 0; i < listOfChooseNum.length; i++) {
                    if (listOfChooseNum[i]) ++haveChooseNum;
                }
                if(haveChooseNum == listOfChooseNum.length) {
                    chooseAll.setImageResource(R.drawable.checkbox_check);
                    haveChooseAll = true;
                }
                haveChoose.setText(String.valueOf(haveChooseNum));
            }
        });
        numOfContext.setText(String.valueOf(list_data.size()));
        haveChoose.setText(String.valueOf(haveChooseNum));
        System.out.println("lihang2: havenum" + haveChooseNum);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("lihangre");
        getList();
    }

    /**
     * 全选联系人
     */
    private void chooseAll() {
        for (int i = 0; i < mListView.getChildCount(); i++) {
            View view = mListView.getChildAt(i);
            ImageView cb = (ImageView) view.findViewById(R.id.cb_list_item_context);
            cb.setImageResource(R.drawable.checkbox_check);
            listOfChooseNum[i] = true;
        }
        haveChoose.setText(String.valueOf(listOfChooseNum.length));
        chooseAll.setImageResource(R.drawable.checkbox_check);
        haveChooseAll = true;
    }

    /**
     * 全不选联系人
     */
    private void unChooseAll() {
        for (int i = 0; i < mListView.getChildCount(); i++) {
            View view = mListView.getChildAt(i);
            ImageView cb = (ImageView) view.findViewById(R.id.cb_list_item_context);
            cb.setImageResource(R.drawable.checkbox_uncheck);
            listOfChooseNum[i] = false;
        }
        haveChoose.setText(String.valueOf(0));
        chooseAll.setImageResource(R.drawable.checkbox_uncheck);
        haveChooseAll = false;
    }

    /**
     * 获取已选择联系人list
     * @return
     */
    public static List<Map<String, Object>> getChooseNameList() {
        List<Map<String, Object>> listToSend = new ArrayList<>();
        for (int i = 0; i < listOfChooseNum.length; i++) {
            if (listOfChooseNum[i]) {
                listToSend.add(list_data.get(i));
            }
        }
        return listToSend;
    }

    /**
     * 判断读取文件和通讯录权限是否开启
     */
    private void canReadFile() {
        int checkReadFilePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int checkReadAddPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
        int all = 0, flag = 0;
        if (checkReadFilePermission != PackageManager.PERMISSION_GRANTED) ++all;
        if (checkReadAddPermission != PackageManager.PERMISSION_GRANTED) ++all;
        String[] perm = new String[all];
        all = 0;
        if (checkReadFilePermission != PackageManager.PERMISSION_GRANTED) {
            perm[all] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            ++all;
            flag = 1;
        }
        if (checkReadAddPermission != PackageManager.PERMISSION_GRANTED) {
            perm[all] = Manifest.permission.READ_CONTACTS;
            ++all;
        }
        if (all != 0) {
            ActivityCompat.requestPermissions(this, perm, 10010);
        }
    }

    //此方法的作用是创建一个选项菜单，我们要重写这个方法
    @SuppressLint("ResourceType")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //加载菜单文件
        getMenuInflater().inflate(R.layout.title_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //在点击这个菜单的时候，会做对应的事，类似于侦听事件，这里我们也要重写它
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //这里是一个switch语句,主要通过menu文件中的id值来确定点了哪个菜单，然后做对应的操作，这里的menu是指你加载的那个菜单文件
        switch (item.getItemId()) {
            case R.id.add:
                Intent intent = new Intent(ContextActivity.this, MainActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("lihangout:");
        for(int i = 0; i < list_data.size(); ++i) {
            if(listOfChooseNum[i]) System.out.print(list_data.get(i).get("Name"));
        }
    }
}
